package cn.tedu.csmall.sso.service.impl;

import cn.tedu.csmall.commons.pojo.admin.model.Admin;
import cn.tedu.csmall.commons.pojo.admin.vo.AdminLoginVO;
import cn.tedu.csmall.sso.mapper.AdminMapper;
import cn.tedu.csmall.sso.utils.AdminUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
       log.info("运行loadUserByUsername方法");
        AdminLoginVO adminLoginVO = adminMapper.userByUsername(s);
        log.info("查询数据库对应的User:{}",adminLoginVO);
        if (adminLoginVO!=null){
            //获取权限
            List<String> permissions = adminLoginVO.getPermissions();
            //把permissions集合中的属性赋值authorities集合中
            List<SimpleGrantedAuthority> authorities=new ArrayList<>();
            for (String p:permissions) {
                authorities.add(new SimpleGrantedAuthority(p));
            }

            AdminUserDetails userDetails = new AdminUserDetails(
                    adminLoginVO.getId(),
                    adminLoginVO.getUsername(),
                    adminLoginVO.getPassword(),
                    adminLoginVO.getEnable() == 1,
                    true,
                    true,
                    true,
                    authorities
            );

            return userDetails;
        }
        return null;
    }
}
